/*
 * @Author: 徐建辰
 * @Date: 2022-02-13 09:15:57
 * @LastEditTime: 2022-02-16 11:12:32
 * @LastEditors: 徐建辰
 * @Description: 
 */
import {defineStore} from 'pinia'
import {Toast} from 'vant'
import router from '@/router'
import {setToken, getToken, getItem} from '@/utils/local'
import {baseName, USER} from '@/utils/constant'
import {hasUser} from '@/utils/utils'
import {login} from '@/service/user'

export default defineStore({
  id: `${baseName}-user`,
  state: () => ({
    token: getToken() || '',
    isLogin: getToken() ? true : false,
    userInfo: getItem(USER) || {}
  }),
  actions: {
    // 用户主动登录
    async login(params) {
      Toast.loading({
        message: '正在登录',
        forbidClick: true,
        loadingType: 'spinner',
      })
      const {data} = await login(params)
      if (!data) {
        Toast({
          message: 'token异常',
          icon: 'close',
        })
        return
      }
      Toast.success('登录成功')
      setToken(data)
      this.token = data
      window.location.href = '/'
    },
    // 获取用户信息
    async getUserInfo() {
      if (!getToken()) {
        router.replace({path: '/login'})
        return
      }
      if (hasUser()) {
        this.userInfo = getItem(USER)
        return
      }
      const {data} = await getUserInfo()
      console.log(data);
      if (!data) return
      userInfo.value = data
      setItem(USER, data)
    }
  },
  getters: {
    gToken: state => state.token,
    gIsLogin: state => state.isLogin
  }
})